let i = localStorage.getItem(`a`) || 1;//键值对的键
let tbody = document.querySelector(`tbody`);//下面的表格
let uname = document.querySelector(`.uname`);//名字
let age = document.querySelector(`.age`);//姓名
let gender = document.querySelector(`.gender`);//性别
let salary = document.querySelector(`.salary`);//工资
let city = document.querySelector(`.city`);//城市
let btn = document.querySelector(`.add`);//按钮
//按钮的点击事件
btn.addEventListener(`click`, function (e) {
  e.preventDefault();
  if (uname.value == `` || age.value == `` || salary.value == ``) {
    alert(`没有填完哦`);
  } else {
    //键值对的值
    let man = JSON.stringify({
      id: i,
      uname: uname.value,
      age: age.value,
      gender: gender.value,
      salary: salary.value,
      city: city.value
    })
    document.querySelector(`form`).reset();
    localStorage.setItem(`${i++}`, `${man}`);
    xr();
    localStorage.setItem(`a`, `${i}`)
  }
})
//表格渲染
//调整把列表数据从自动添加变为由数组添加
function xr() {
  tbody.innerHTML = ``;
  for (let index = 0; index < i; index++) {
    let man = JSON.parse(localStorage.getItem(`${index}`))
    if (man == null) { continue; }
    else if (man != null) {
      let table = document.createElement(`tr`);
      table.innerHTML =
        `<td>${man.id}</td>
        <td>${man.uname}</td>
        <td>${man.age}</td>
        <td>${man.gender}</td>
        <td>${man.salary}</td>
        <td>${man.city}</td>
        <td>
        <a href="javascript:" data-id=${man.id} class="del">删除</a>
        </td>`
      tbody.appendChild(table);
    }
  }
}
//获取表单对象当点击时如果时a标签则删
tbody.addEventListener(`click`, function (e) {
  if (e.target.tagName === `A`) {
    localStorage.removeItem(`${e.target.dataset.id}`)
    xr();
  }
})
xr();